package cn.hinglo.gameclaw.admin.action;

import cn.hinglo.gameclaw.admin.service.BannerService;
import cn.hinglo.gameclaw.data.controller.BaseController;
import cn.hinglo.gameclaw.data.entity.Result;
import cn.hinglo.gameclaw.user.bean.Banner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

/**
 * @createTime: 2017/12/29
 * @author: HingLo
 * @description: banner图管理
 */
@RestController
@RequestMapping("admin/b/")
@Slf4j
@CacheConfig(cacheNames = "banner")
public class BannerAction extends BaseController {
    private final BannerService bannerService;

    @Autowired
    public BannerAction(BannerService bannerService) {
        this.bannerService = bannerService;
    }

    /**
     * 浏览Banner图片
     *
     * @return 操作结果
     */
    @GetMapping("list")
    public Result listBanner() {
        return success(bannerService.listBannerService());
    }

    /**
     * 添加banner图
     *
     * @param banner Banner对象
     * @param image  banner图片
     * @return 操作结果
     */
    @PostMapping(value = "add")
    public Result addBanner(@Valid Banner banner, BindingResult bindingResult, @RequestParam("image") MultipartFile image) {
        if (bindingResult.hasErrors()) {
            return error(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean bool = bannerService.addBannerService(banner, image);
        return bool ? success() : error("Banner图添加失败");
    }

    /**
     * 删除banner图
     *
     * @return 操作结果
     */
    @DeleteMapping("delete")
    public Result deleteBanner(String id) {
        return bannerService.deleteBannerService(id);
    }

    /**
     * 修改banner图的使用状态
     *
     * @param id     banner id
     * @param status 设置的状态
     * @return 操作结果
     */
    @PutMapping("update")
    @CacheEvict(allEntries = true)
    public Result changeBanner(String id, boolean status) {
        return bannerService.changeBannerService(id, status);
    }
}
